#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
综合优化脚本 - 自动检测和修复项目中的常见问题
"""

import os
import sys
import json
import ast
import re
import subprocess
import socket
import time
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Tuple, Any

class ProjectOptimizer:
    def __init__(self, project_root: str = None):
        self.project_root = Path(project_root) if project_root else Path(__file__).parent.parent
        self.issues_found = []
        self.fixes_applied = []
        self.optimization_results = {}
        
    def log_issue(self, issue_type: str, description: str, severity: str = "medium", file_path: str = None):
        """记录发现的问题"""
        issue = {
            "type": issue_type,
            "description": description,
            "severity": severity,
            "file_path": file_path,
            "timestamp": datetime.now().isoformat()
        }
        self.issues_found.append(issue)
        print(f"🔍 发现问题: {description} (严重程度: {severity})")
        
    def log_fix(self, fix_type: str, description: str, file_path: str = None):
        """记录应用的修复"""
        fix = {
            "type": fix_type,
            "description": description,
            "file_path": file_path,
            "timestamp": datetime.now().isoformat()
        }
        self.fixes_applied.append(fix)
        print(f"✅ 应用修复: {description}")
        
    def check_syntax_errors(self) -> bool:
        """检查Python文件的语法错误"""
        print("\n🔍 检查语法错误...")
        syntax_errors = []
        
        for py_file in self.project_root.rglob("*.py"):
            try:
                with open(py_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                ast.parse(content)
            except SyntaxError as e:
                syntax_errors.append((py_file, e))
                self.log_issue("syntax_error", f"语法错误: {e}", "high", str(py_file))
            except Exception as e:
                self.log_issue("file_error", f"文件读取错误: {e}", "medium", str(py_file))
                
        return len(syntax_errors) == 0
        
    def fix_import_issues(self) -> bool:
        """修复导入问题"""
        print("\n🔧 修复导入问题...")
        
        # 确保所有必要的__init__.py文件存在
        directories_to_init = [
            self.project_root,
            self.project_root / "apps",
            self.project_root / "scripts", 
            self.project_root / "modules",
            self.project_root / "modules" / "exploits",
            self.project_root / "modules" / "automation",
            self.project_root / "modules" / "evasion",
            self.project_root / "modules" / "intelligence"
        ]
        
        for dir_path in directories_to_init:
            if dir_path.exists() and dir_path.is_dir():
                init_file = dir_path / "__init__.py"
                if not init_file.exists():
                    init_file.write_text("# -*- coding: utf-8 -*-\n")
                    self.log_fix("init_file", f"创建 {init_file}", str(init_file))
                    
        # 检查并修复相对导入
        for py_file in self.project_root.rglob("*.py"):
            try:
                with open(py_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                    
                # 查找相对导入
                relative_imports = re.findall(r'from\s+\.+\w*\s+import', content)
                if relative_imports:
                    self.log_issue("relative_import", f"发现相对导入: {relative_imports}", "medium", str(py_file))
                    
            except Exception as e:
                self.log_issue("import_check_error", f"导入检查错误: {e}", "low", str(py_file))
                
        return True
        
    def optimize_network_connectivity(self) -> bool:
        """优化网络连接"""
        print("\n🌐 优化网络连接...")
        
        target_host = "192.168.10.129"
        target_port = 8888
        
        # 测试连接稳定性
        success_count = 0
        total_tests = 10
        
        for i in range(total_tests):
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(3)
                result = sock.connect_ex((target_host, target_port))
                sock.close()
                
                if result == 0:
                    success_count += 1
                time.sleep(0.5)
                
            except Exception as e:
                self.log_issue("network_error", f"网络测试错误: {e}", "low")
                
        success_rate = (success_count / total_tests) * 100
        self.optimization_results["network_stability"] = success_rate
        
        if success_rate < 80:
            self.log_issue("network_instability", f"网络连接不稳定，成功率: {success_rate}%", "medium")
            
            # 创建网络优化配置
            network_config = {
                "connection_timeout": 5,
                "retry_attempts": 3,
                "retry_delay": 1,
                "keep_alive": True
            }
            
            config_file = self.project_root / "config" / "network_optimization.json"
            config_file.parent.mkdir(exist_ok=True)
            
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(network_config, f, indent=2, ensure_ascii=False)
                
            self.log_fix("network_optimization", f"创建网络优化配置", str(config_file))
        else:
            print(f"✅ 网络连接稳定，成功率: {success_rate}%")
            
        return success_rate >= 60
        
    def check_dependencies(self) -> bool:
        """检查依赖包"""
        print("\n📦 检查依赖包...")
        
        requirements_file = self.project_root / "requirements.txt"
        if not requirements_file.exists():
            self.log_issue("missing_requirements", "缺少requirements.txt文件", "medium")
            return False
            
        try:
            with open(requirements_file, 'r', encoding='utf-8') as f:
                requirements = f.read().strip().split('\n')
                
            missing_packages = []
            for req in requirements:
                if req.strip() and not req.startswith('#'):
                    package_name = req.split('==')[0].split('>=')[0].split('<=')[0].strip()
                    try:
                        __import__(package_name)
                    except ImportError:
                        missing_packages.append(package_name)
                        
            if missing_packages:
                self.log_issue("missing_dependencies", f"缺少依赖包: {missing_packages}", "high")
                return False
            else:
                print("✅ 所有依赖包已安装")
                return True
                
        except Exception as e:
            self.log_issue("dependency_check_error", f"依赖检查错误: {e}", "medium")
            return False
            
    def optimize_file_permissions(self) -> bool:
        """优化文件权限"""
        print("\n🔐 优化文件权限...")
        
        script_files = list(self.project_root.rglob("*.py"))
        shell_files = list(self.project_root.rglob("*.sh"))
        
        for script_file in script_files + shell_files:
            try:
                # 在Windows上，我们主要检查文件是否可读写
                if not os.access(script_file, os.R_OK | os.W_OK):
                    self.log_issue("permission_error", f"文件权限不足: {script_file}", "medium", str(script_file))
                    
            except Exception as e:
                self.log_issue("permission_check_error", f"权限检查错误: {e}", "low", str(script_file))
                
        return True
        
    def create_optimization_summary(self) -> Dict[str, Any]:
        """创建优化摘要"""
        summary = {
            "optimization_time": datetime.now().isoformat(),
            "project_root": str(self.project_root),
            "total_issues_found": len(self.issues_found),
            "total_fixes_applied": len(self.fixes_applied),
            "issues_by_severity": {
                "high": len([i for i in self.issues_found if i["severity"] == "high"]),
                "medium": len([i for i in self.issues_found if i["severity"] == "medium"]),
                "low": len([i for i in self.issues_found if i["severity"] == "low"])
            },
            "optimization_results": self.optimization_results,
            "issues_found": self.issues_found,
            "fixes_applied": self.fixes_applied
        }
        
        return summary
        
    def run_comprehensive_optimization(self) -> bool:
        """运行综合优化"""
        print("🚀 开始综合优化...")
        print(f"项目路径: {self.project_root}")
        
        optimization_steps = [
            ("语法检查", self.check_syntax_errors),
            ("导入问题修复", self.fix_import_issues),
            ("网络连接优化", self.optimize_network_connectivity),
            ("依赖包检查", self.check_dependencies),
            ("文件权限优化", self.optimize_file_permissions)
        ]
        
        results = {}
        overall_success = True
        
        for step_name, step_func in optimization_steps:
            print(f"\n{'='*50}")
            print(f"执行步骤: {step_name}")
            print(f"{'='*50}")
            
            try:
                result = step_func()
                results[step_name] = result
                if not result:
                    overall_success = False
                    print(f"❌ {step_name} 失败")
                else:
                    print(f"✅ {step_name} 成功")
                    
            except Exception as e:
                results[step_name] = False
                overall_success = False
                self.log_issue("optimization_error", f"{step_name} 执行错误: {e}", "high")
                print(f"❌ {step_name} 执行错误: {e}")
                
        # 生成优化报告
        summary = self.create_optimization_summary()
        summary["step_results"] = results
        summary["overall_success"] = overall_success
        
        # 保存JSON报告
        reports_dir = self.project_root / "reports"
        reports_dir.mkdir(exist_ok=True)
        
        json_report = reports_dir / "comprehensive_optimization_report.json"
        with open(json_report, 'w', encoding='utf-8') as f:
            json.dump(summary, f, indent=2, ensure_ascii=False)
            
        # 生成Markdown报告
        md_report = reports_dir / "comprehensive_optimization_report.md"
        self.generate_markdown_report(summary, md_report)
        
        print(f"\n{'='*60}")
        print("🎯 优化完成!")
        print(f"总问题数: {len(self.issues_found)}")
        print(f"总修复数: {len(self.fixes_applied)}")
        print(f"整体成功: {'✅' if overall_success else '❌'}")
        print(f"报告保存至: {json_report}")
        print(f"详细报告: {md_report}")
        print(f"{'='*60}")
        
        return overall_success
        
    def generate_markdown_report(self, summary: Dict[str, Any], output_file: Path):
        """生成Markdown格式的优化报告"""
        content = f"""# 综合优化报告

**优化时间**: {summary['optimization_time']}
**项目路径**: {summary['project_root']}

## 📊 优化统计

- **发现问题总数**: {summary['total_issues_found']}
- **应用修复总数**: {summary['total_fixes_applied']}
- **整体成功**: {'✅ 是' if summary.get('overall_success', False) else '❌ 否'}

### 问题严重程度分布

- **高严重程度**: {summary['issues_by_severity']['high']} 个
- **中等严重程度**: {summary['issues_by_severity']['medium']} 个  
- **低严重程度**: {summary['issues_by_severity']['low']} 个

## 🔧 优化步骤结果

"""
        
        if 'step_results' in summary:
            for step, result in summary['step_results'].items():
                status = "✅ 成功" if result else "❌ 失败"
                content += f"- **{step}**: {status}\n"
                
        content += "\n## 🌐 网络优化结果\n\n"
        if 'network_stability' in summary['optimization_results']:
            stability = summary['optimization_results']['network_stability']
            content += f"- **网络连接稳定性**: {stability:.1f}%\n"
            
        content += "\n## 🔍 发现的问题\n\n"
        for i, issue in enumerate(summary['issues_found'], 1):
            severity_emoji = {"high": "🔴", "medium": "🟡", "low": "🟢"}
            emoji = severity_emoji.get(issue['severity'], "⚪")
            content += f"### {i}. {emoji} {issue['description']}\n"
            content += f"- **类型**: {issue['type']}\n"
            content += f"- **严重程度**: {issue['severity']}\n"
            if issue.get('file_path'):
                content += f"- **文件**: {issue['file_path']}\n"
            content += "\n"
            
        content += "## ✅ 应用的修复\n\n"
        for i, fix in enumerate(summary['fixes_applied'], 1):
            content += f"### {i}. {fix['description']}\n"
            content += f"- **类型**: {fix['type']}\n"
            if fix.get('file_path'):
                content += f"- **文件**: {fix['file_path']}\n"
            content += "\n"
            
        content += """## 📋 建议

### 高优先级
- 修复所有高严重程度问题
- 确保语法错误完全解决
- 验证网络连接稳定性

### 中等优先级  
- 优化导入结构
- 完善依赖管理
- 提升代码质量

### 低优先级
- 优化文件组织
- 完善文档
- 性能调优

## 🎯 结论

"""
        
        if summary.get('overall_success', False):
            content += "项目优化成功完成！所有主要问题已得到解决，项目现在处于良好状态。"
        else:
            content += "项目优化部分完成。仍有一些问题需要手动处理，请查看上述问题列表并逐一解决。"
            
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(content)

def main():
    """主函数"""
    optimizer = ProjectOptimizer()
    success = optimizer.run_comprehensive_optimization()
    
    return 0 if success else 1

if __name__ == "__main__":
    sys.exit(main())